package com.xingkeduo.business.transformation.json;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.query.ConsumerQO;
import com.xingkeduo.pojo.table.ConsumerTO;
import com.xingkeduo.pojo.utils.Base64Utils;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;

import com.xingkeduo.util.tool.RegularUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/2/19 10:32
 **/
@Component
public class ConsumerJTO extends BaseJson {

    /**
     * 入参json
     *
     * @param json:
     * @return : com.xingkeduo.pojo.query.ConsumerQO
     * @author : gaozifeng
     * @date : 2019/2/28 11:00
     */
    public static ConsumerQO createQueryForList(String json) throws Throwable {
        ConsumerQO query = new ConsumerQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setCondition(validCondition(root, YesNoEnum.NO)).setId(validId(root, YesNoEnum.NO)).setFans(validInteger(root, "weChatFans", 2, YesNoEnum.NO));
        query.setType(validType(root, YesNoEnum.NO));
        if (root.has("ids")) {
            if (!root.path("ids").isArray()) {
                throw new InputParamException(InputParamException.Type.INVALID, "评分");
            } else {
                List<Long> list = new ArrayList<>(10);
                JsonNode ids = root.path("ids");
                ids.forEach((JsonNode node) -> {
                    list.add(Long.parseLong(String.valueOf(node)));
                });
                query.setIds(list);
            }
        }

        return query;
    }

    /**
     * 外部接口 condition  营销 id，phone 统一用condition
     * nameOrPhone 订单 id,name,phone  id用id  其他用nameOrPhone
     *
     * @param json:
     * @return : com.xingkeduo.pojo.query.ConsumerQO
     * @author : gaozifeng
     * @date : 2019/6/13 10:19
     */
    public static ConsumerQO createQueryForCondition(String json) throws Throwable {
        ConsumerQO query = new ConsumerQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;
        String value = null;
        query.setId(validPrimary(root, "id", YesNoEnum.NO));
        if (root.has("condition")) {
            value = root.path("condition").asText().trim();
            if (RegularUtil.isPositiveInteger(value)) {
                if (value.length() != 11) {
                    query.setId(Long.parseLong(value));
                }
            } else {
                //名字
                String encodeParam = Base64Utils.encodeParam(value);
                query.setCondition(encodeParam);
            }
        }
        //订单不进行模糊匹配用户名称
        if (root.has("nameOrPhone")) {
            value = root.path("nameOrPhone").asText().trim();
            if (RegularUtil.isPositiveInteger(value)) {
                if (value.length() != 11) {
                    //可能用户名字是数字
                    String encodeParam = Base64Utils.encodeParam(value);
                    query.setNameOrPhone(encodeParam);
                } else {
                    //手机号
                }
            } else {
                //名字
                String encodeParam = Base64Utils.encodeParam(value);
                query.setNameOrPhone(encodeParam);
            }
        }
        return query;
    }


    public static Integer validType(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "userType";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (StringUtils.isNotEmpty(value)) {
                return Integer.valueOf(value);
            } else {
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            }
        }
        return 0;
    }


    public static ConsumerQO createQueryForBinDing(String json) throws Throwable {
        ConsumerQO query = new ConsumerQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setLogin(validString(root, "login", 80, YesNoEnum.YES));
        return query;
    }

    public static ConsumerQO createQueryForPrimary(String json) throws Throwable {
        ConsumerQO query = new ConsumerQO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        query.setId(validId(root, YesNoEnum.YES));
        return query;
    }

    public static ConsumerQO createQuery(String json) throws Throwable {
        ConsumerQO query = new ConsumerQO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        query.setId(validId(root, YesNoEnum.NO)).setLogin(validString(root, "login", 80, YesNoEnum.NO));
//        query.setId(validId(root, YesNoEnum.NO)).setLogin(validString(root, "login", 80, YesNoEnum.NO)).setOpenId(validString(root, "openid", 80, YesNoEnum.NO));
        return query;
    }

    /**
     * 返回实体信息
     *
     * @param table:
     * @return : com.fasterxml.jackson.databind.node.ObjectNode
     * @author : gaozifeng
     * @date : 2019/2/19 16:24
     */
    public static ObjectNode toJson(ConsumerTO table) throws Throwable {
        ObjectNode root = MAPPER.createObjectNode();
        if (table != null) {
            root.put("login", table.getLogin());
            root.put("name", StringUtils.isNotEmpty(table.getName()) ? Base64Utils.decoderParam(table.getName()) : "");//昵称
            root.put("type", table.getType());
            root.put("createdtime", table.getCreatedTime() == null ? "" : table.getCreatedTime().toString());
            root.put("fans", table.getFans());
//            root.put("openId", table.getOpenId());
            if (null != table.getFileTO()) {
                root.put("userphoto", table.getFileTO().getPath());
            }

            if (table.getPrivateTO() != null) {
                root.put("openId", null == table.getPrivateTO().getMinaOpenId() ? null : table.getPrivateTO().getMinaOpenId());
                root.put("openId", null == table.getPrivateTO().getGzhOpenId() ? null : table.getPrivateTO().getGzhOpenId());
                if (null != table.getPrivateTO().getSex()) {//性别
                    root.put("sex_value", table.getPrivateTO().getSex().getValue());
                    root.put("sex_desc", table.getPrivateTO().getSex().getDesc());
                }
                if (null != table.getPrivateTO().getDistance()) {//到店距离
                    root.put("distance", table.getPrivateTO().getDistance());
                }
                if (null != table.getPrivateTO().getCareer()) {//职业属性
                    root.put("career", table.getPrivateTO().getCareer());
                }
                if (table.getPrivateTO().getAge() != null)//年龄
                    root.put("age", table.getPrivateTO().getAge());
                if (table.getPrivateTO().getPhone() != null)//手机号
                    root.put("phone", table.getPrivateTO().getPhone());
                if (StringUtils.isNotEmpty(table.getPrivateTO().getCityId()))//城市
                    root.put("city", table.getPrivateTO().getCityId());
            }
            if (table.getIsDelete() != null) {
                root.put("isdelete_value", table.getIsDelete().getValue());
                root.put("isdelete_desc", table.getIsDelete().getDesc());
            }
            root.put("firstConsumer", "-");//首次服务时间
            root.put("lastConsumer", "-");//上次服务时间
            if (null != table.getTo()) {//统计信息
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                root.put("serviceTotal", table.getTo().getServiceTotal());
                root.put("serviceMoney", table.getTo().getServiceMoney());
                root.put("lastServiceTime", table.getTo().getLastTime() == null ? "" : sdf.format(table.getTo().getLastTime()));
                root.put("refundMoney", table.getTo().getRefundMoney());
                root.put("firstConsumer", table.getTo().getCreatedTime() == null ? "" : sdf.format(table.getTo().getCreatedTime()));
                root.put("lastConsumer", table.getTo().getUpdatedTime() == null ? "" : sdf.format(table.getTo().getUpdatedTime()));
            } else {
                root.put("serviceTotal", "-");
                root.put("serviceMoney", "-");
            }

            //风格定位
            if (table.getStyleList() != null && table.getStyleList().size() > 0) {
                if (table.getStyleList().size() == 1) {
                    root.put("styleInfo", StringUtils.isNotEmpty(table.getStyleList().get(0).getStyle()) ? table.getStyleList().get(0).getStyle() : "");
                } else {
                    root.put("styleInfo", StringUtils.isNotEmpty(table.getStyleList().get(table.getStyleList().size() - 1).getStyle()) ? table.getStyleList().get(table.getStyleList().size() - 1).getStyle() + "等" : "");
                }
            }

            toBaseJson(root, table);
        }
        return root;
    }

    public static ObjectNode toJsonById(ConsumerTO table) throws Throwable {
        ObjectNode root = MAPPER.createObjectNode();
        if (table != null) {
            toBaseJson(root, table);
        }
        return root;
    }


    /**
     * 返回集合
     *
     * @param tables:
     * @return : com.fasterxml.jackson.databind.node.ArrayNode
     * @author : gaozifeng
     * @date : 2019/2/19 16:25
     */
    public static ArrayNode toJson(List<ConsumerTO> tables) throws Throwable {
        ArrayNode root = MAPPER.createArrayNode();

        if (!CommonUtil.isEmpty(tables)) {
            for (Iterator<ConsumerTO> iterator = tables.iterator(); iterator.hasNext(); ) {
                root.add(toJson(iterator.next()));
            }
        }
        return root;
    }

    public static ConsumerTO createTableForNew(String json) throws Throwable {
        ConsumerTO table = new ConsumerTO();
        JsonNode root = validJson(json);
        if (root == null) {
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        }
        table.setLogin(validString(root, "login", 32, YesNoEnum.NO)).setName(validString(root, "name", 30, YesNoEnum.NO)).setFans(validInteger(root, "fans", 3, YesNoEnum.NO))
                .setType(validInteger(root, "type", 1, YesNoEnum.NO)).setCode(validCode(root, YesNoEnum.NO));
        return table;
    }

    public static String validCondition(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "condition";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if ("".equals(value)) {
                return value;
            }
            if (CommonUtil.isEmpty(value) || value.length() > 20)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return value;
        }
        return null;
    }

    public static int validInteger(JsonNode node, String key, int max, YesNoEnum isRequired) throws Throwable {
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();

            if (CommonUtil.isEmpty(value) || value.length() > max)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return Integer.valueOf(value);
        }
        return 0;
    }

    /**
     * 返回json转List
     *
     * @param jsonString:
     * @param clazz:
     * @return : java.util.List<T>
     * @author : gaozifeng
     * @date : 2019/5/2 19:47
     */
    public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
        List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz);
        return ts;
    }
}
